package cn.lhf.cd.controller;

import cn.lhf.cd.FXApplication;
import cn.lhf.cd.Main;
import cn.lhf.cd.annotation.FXController;
import cn.lhf.cd.mapper.UserMapper;
import cn.lhf.cd.utils.StringUtils;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import org.apache.ibatis.session.SqlSession;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

@FXController(path = "/ui/login.fxml")
public class LoginController extends ChildrenController {
    public ComboBox<String> accountCombo;
    public PasswordField passwordField;
    public Label tipLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        SqlSession sqlSession = Main.openSqlSession();
        ArrayList<String> items = new ArrayList<>();    //帐号表
        for (Integer x : sqlSession.getMapper(UserMapper.class).getIds()) {
            items.add(x.toString());
        }
        accountCombo.setItems(FXCollections.observableList(items)); //填充帐号表
        accountCombo.valueProperty().addListener((observable, oldValue, newValue) -> {  //监听选择事件
            if (StringUtils.isEmpty(newValue))  //没有选择
                return;
            SqlSession iSqlSession = Main.openSqlSession();
            passwordField.setText(iSqlSession.getMapper(UserMapper.class).getPassword(Integer.parseInt(newValue))); //填充密码
            iSqlSession.close();
        });
        sqlSession.close();
    }

    public String getAccount() {
        return accountCombo.getValue();
    }

    public String getPassword() {
        return passwordField.getText();
    }

    @Override
    public String getTitle() {
        return "登录界面";
    }

    @Override
    public void onBtnRight4() throws Exception {
        String account = getAccount();
        if (StringUtils.isEmpty(account)) {
            sendTip(tipLabel, "请选择帐户！");
            return;
        }
        String password = getPassword();
        if (StringUtils.isEmpty(password)) {
            sendTip(tipLabel, "请输入密码！");
            return;
        }

        Integer id = Integer.parseInt(account);

        SqlSession sqlSession = Main.openSqlSession();
        if (sqlSession.getMapper(UserMapper.class).login(id, password)) {   //登录
            clearTips();    //消除所有提示
            getMainController().setSelfId(id);  //保存登的帐号
            getMainController().setFrameView(HomeController.class); //跳转至首页
        } else {
            sendTip(tipLabel, "密码错误！");
        }
        sqlSession.close();
    }

    @Override
    public void onBtnLeft4() {
        FXApplication.close();
    }
}
